﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DataAccess;

namespace CreatePGSQLDataScript
{
    public partial class SearchProc : Form
    {
        public SearchProc()
        {
            InitializeComponent();
        }
        PgSqlProvider db;


        Dictionary<int, string> funcContextList = new Dictionary<int, string>();

        private void btnConnect_Click(object sender, EventArgs e)
        {
            try
            {
                db = new PgSqlProvider(comboBox1.Text);
                db.Open();
                historyList.SaveValue(comboBox1);
                MessageBox.Show("連接成功！");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            if (db == null)
            {
                MessageBox.Show("未连接到服务器");
                return;
            }

            //string sqlText = richTextBox1.Text;
            //DataTable dt = db.GetDataTable(sqlText);
            //dataGridView1.DataSource = dt;

            //可能一个名字有多个。麻烦。可能还要选择一下。 


            funcContextList.Clear();
            listBox1.Items.Clear();

            string sqlText = string.Format(@"select proname,proargtypes,
                                            coalesce(prosrc,'') as prosrc
                                            ,proargnames,pronargs,pg_type.typname
                                            from pg_proc 
                                            left join pg_type on pg_type.oid=pg_proc.prorettype
                                            where prolang = '16386' and pg_proc.proname='{0}'",textBox1.Text.Trim());

            DataTable dt = db.GetDataTable(sqlText);

            if (dt.Rows.Count <= 0)
                return;
 

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dt.Rows[i];
                string procName = dr["proname"].ToString();
                //string paramter = getParamters(procName, dtParamer);
                string paramter = getParam(dr["proargtypes"].ToString(), dr["proargnames"]);

                //string returnInfo = getReturnInfo(procName, dtReturnInfo);
                string returnInfo = getReturnInfo(dr["typname"].ToString());

                StringBuilder sb = new StringBuilder();

                sb.Append(string.Format("CREATE OR REPLACE FUNCTION {0}({1})", procName, paramter));
                sb.Append(returnInfo);
                sb.Append(dr["prosrc"].ToString());
                sb.Append("$$ LANGUAGE 'plpgsql'");
                rtxtContext.Text  = sb.ToString();

                funcContextList[i] = sb.ToString();
                listBox1.Items.Add(i.ToString());
            }

            if (funcContextList.Count > 0)
            {
                rtxtContext.Text = funcContextList[0];
            }

 
        }
        private string getReturnInfo(string datatype)
        {
            if (datatype == "record")
                datatype = "setof record";

            return "\nRETURNS " + datatype + " AS \n$$ ";
        }

        public string getParam(string types, object obj)
        {
            string[] namelist = { };
            if (obj != DBNull.Value)
            {
                namelist = (string[])obj;
            }
            types = types.Replace("1043", "varchar");
            types = types.Replace("23", "int");
            types = types.Replace("1700", "numeric");

            string[] typelist = types.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

            string parmeall = "";
            for (int i = 0; i < typelist.Length; i++)
            {
                if (parmeall != "")
                {
                    parmeall += "," + typelist[i] + " " + namelist[i];
                }
                else
                {
                    parmeall += typelist[i] + " " + namelist[i];
                }

            }
            return parmeall;

        }
        private void SearchProc_Load(object sender, EventArgs e)
        {
            historyList.ReadList(comboBox1);
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            rtxtContext.Text = funcContextList[listBox1.SelectedIndex];
        }
    }
}
